import axios from 'axios'

const errorHandle = (cb, errorMsg) => {
  if (!errorMsg) return
  cb(errorMsg)
  throw errorMsg
}

const request = async (url = '', data = {}, opt = {}) => {
  const method = (opt && opt.method) || 'get'
  try {
    const res = await axios({ baseURL: '/gitee', method, url, data, ...opt })
    return { data: res.data, error: cb => errorHandle(cb) }
  } catch (error) {
    return { error: cb => errorHandle(cb, error) }
  }
}
request.get = (url, data, opt = {}) => request(url, data, { ...opt, method: 'get' })
request.post = (url, data, opt = {}) => request(url, data, { ...opt, method: 'post' })
request.put = (url, data, opt = {}) => request(url, data, { ...opt, method: 'put' })
request.delete = (url, data, opt = {}) => request(url, data, { ...opt, method: 'delete' })

export default request
